package com.xiguaji.tiktok.config.interceptor;


import com.xiguaji.boot.toolkit.HttpUtil;
import com.xiguaji.boot.toolkit.JsonUtil;
import com.xiguaji.tiktok.utils.Ret;
import com.xiguaji.tiktok.utils.jwt.JwtUser;
import com.xiguaji.tiktok.utils.jwt.JwtUtil;
import com.xiguaji.tiktok.v1.user.model.User;
import com.xiguaji.tiktok.v1.user.service.UserService;
import com.xiguaji.tiktok.v1.user.validate.UserHandler;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    UserService userService;

    @Autowired
    JwtUtil jwtUtil;

    @Value("${jwt.head}")
    String authorized;

    @Value("${server.servlet.session.cookie.domain}")
    String domain;

    @Autowired
    UserHandler userHandler;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        String token = HttpUtil.getCookie(authorized);

        if(!StringUtils.isEmpty(token)){
            if(userService.validaToken(token)){
                return true;
            }
        }

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        val writer = response.getWriter();
        writer.write(unauthorizedType(token));// Unauthorized
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) {
        // TODO Auto-generated method stub

    }
    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        // 刷新token
        String token = HttpUtil.getCookie(authorized);
        if(userService.validaToken(token)){
            if(jwtUtil.isRefresh(token)){
                JwtUser jwtUser = jwtUtil.getJwtUserByToken(token);
                User user = JsonUtil.jsonParse(User.class, JsonUtil.parseJson(jwtUser.getUser()));;
                String newToken = userService.login(user);
                userHandler.setLoginCookie(newToken);
            }
        }
    }

    private String unauthorizedType(String token){
        if(!StringUtils.isEmpty(token)){
            val user = jwtUtil.getJwtUserByToken(token);
            if(user.getExpiration().getTime() > System.currentTimeMillis()){
                userHandler.setLoginCookie("");

                if(null != userHandler.getUser()){
                    userHandler.redisTemplate.delete(String.valueOf(userHandler.getUser().getId()));
                }
                return Ret.userAlready();
            }
        }
        return Ret.userExpired();
    }
}
